<?php
/**
 * Created by PhpStorm.
 * User: shkj
 * Date: 2020/8/29
 * Time: 23:16
 */

namespace app\api\service;


use app\lib\enum\ScopeEnum;
use think\Exception;
use app\api\model\User as UserModel;
class UserToken extends Token
{
    protected $code;
    protected $wxAppID;
    protected $wxAppSecret;
    protected $wxLoginUrl;

    function __construct($code)
    {
        $this->code = $code;
        $this->wxAppID = config('wx.app_id');
        $this->wxAppSecret = config('wx.app_secret');
        $this->wxLoginUrl = sprintf(config('wx.login_url'), $this->wxAppID,$this->wxAppSecret,$this->code);

    }

    public function get($res=''){
        $result = curl_get($this->wxLoginUrl);

        $wxResult = json_decode($result,true);
        if(empty($wxResult)){
            throw new Exception('获取session_key及openID时异常，微信内部错误');
        }else{
            $loginFail = array_key_exists('errcode',$wxResult);
            if($loginFail){
                $this->processLoginError($wxResult);
            }else{
                return $this->grantToken($wxResult,$res);
            }
        }
    }

    private function grantToken($wxResult,$res){
        //拿到oppenid
        //数据库里看下，openid时不时已经存在
        //如果存在则不处理，否则新增一条user记录
        //生成令牌，准备缓存数据，写入缓存
        //把令牌返回到客户端去
        //key:令牌
        //value:wxResult,uid,scope

        $openid = $wxResult['openid'];
        $user = UserModel::getByOpenID($openid);
        if($user){
            $uid = $user->id;
            db('user')->where('id',$uid)->update($res);
        }else{
            $uid = $this->newUser($openid,$res);
        }
        $cachedValue = $this->prepareCahedValue($wxResult,$uid);
        $token = $this->saveToCache($cachedValue);
        $user = db('user')->field('money,integral')->where('id',$uid)->find();
        $info = array(
          'uid'=>$uid,
          'token'=>$token,
          'money'=>$user['money'],
          'integral'=>$user['integral']
            );
        return $info;
    }

//传uid和token，让uid做key
    private function saveToCache($cachedValue){
        $token = self::generateToken();
        $cachedValue['token'] = $token;
        $value = json_encode($cachedValue);
        $expire_in = config('setting.token_expire_in');

        $request = cache($cachedValue['uid'],$value,$expire_in);
        if(!$request){
            return_json(10005,'服务器缓存异常');

        }
        return $token;
    }

    private function prepareCahedValue($wxResult,$uid){
        $cachedValue = $wxResult;
        $cachedValue['uid'] = $uid;
        //scope=16代表App用户的权限数值
        $cachedValue['scope'] = ScopeEnum::User;

        //scope=32 代表CMS（管理员）用户的权限数值
//        $cachedValue['scope'] = 32;
        return $cachedValue;
    }
    private function newUser($openid,$res){
        $res['openid'] = $openid;

        $id = db('user')->insertGetId($res);
        return $id;
    }



    private function processLoginError($wxResult){
        return_json($wxResult['errcode'],$wxResult['errmsg']);
//        throw new WeChatException(
//            [
//                'msg' => $wxResult['errmsg'],
//                'errorCode' => $wxResult['errcode']
//
//            ]);

    }
}